package v1

import (
	"bytes"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"io/ioutil"
	"zimuzu_cvn_web_api/config"
	"zimuzu_cvn_web_api/model"
	. "zimuzu_cvn_web_api/pkg/e"
	"zimuzu_cvn_web_api/pkg/errno"
	"zimuzu_cvn_web_api/pkg/util"
	"zimuzu_cvn_web_api/router/api"
	"zimuzu_cvn_web_api/router/api/app/middleware"
	"zimuzu_cvn_web_api/service"
)

type UsdtAPI struct {
}

func (usdt UsdtAPI) Name() string {
	return "usdt API"
}

func (usdt UsdtAPI) Bind() {
	UsdtAPI := config.C.Router.Group("/v1/app/usdt", middleware.TrackLog(), middleware.AuthMiddleware())
	{
		UsdtAPI.GET("serviceCharge", usdtServiceCharge)
		UsdtAPI.GET("balance", usdtBalance)
		UsdtAPI.POST("transfer", usdtTransfer)
	}
}

//手续费
//Auth: TXG
func usdtServiceCharge(c *gin.Context) {
	var data model.ServiceCharge
	data.Charge = service.GetUsdtCharges()
	errno.OK.Info = "OK"
	api.SendResponse(c, errno.OK, data)
	return
}

//账户可用余额
//Auth: TXG
func usdtBalance(c *gin.Context) {
	uid, _ := service.GetUserIdByRequest(c)
	data, err := service.GetUsdtAmountBalance(uid)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	errno.OK.Info = "OK"
	api.SendResponse(c, errno.OK, data)
	return
}

//转账提交
//Auth: TXG
func usdtTransfer(c *gin.Context) {
	var (
		getData      model.Sign
		postData     model.TransferParam
		responseData model.Id
	)
	userId, _ := c.Get("userId")
	uid := userId.(int64)
	author := c.Request.Header.Get("Authorization")
	//获取get参数
	if err := c.ShouldBindWith(&getData, binding.Query); err != nil {
		api.SendResponse(c, errno.ParamsError, nil)
		return
	}
	sign := getData.Sign
	//获取body
	bodyBytes, err := ioutil.ReadAll(c.Request.Body)
	bodyStr := string(bodyBytes)
	Log("info", bodyStr)
	if err != nil {
		api.SendResponse(c, errno.ParamsError, nil)
		return
	}
	c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
	if err := c.ShouldBindWith(&postData, binding.FormPost); err != nil {
		api.SendResponse(c, errno.ParamsError, nil)
		return
	}
	ok, err := util.AppCheckSign(bodyStr, author, sign)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	if !ok {
		api.SendResponse(c, errno.ParamsError, nil)
		return
	}
	id, err := service.UsdtTransfer(uid, author, postData)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	responseData.Id = id
	errno.OK.Info = "OK"
	api.SendResponse(c, errno.OK, responseData)
	return
}